﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace NuaTarDoneng
{
    /// <summary>
    /// WallPaper 的摘要说明
    /// </summary>
    public class WallPaper : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (null == context.Request.QueryString["action"])
            {
                context.Response.Write("Hello,World!");
            }
            else if ("AddSQL" == context.Request.QueryString["action"]) {
                string cmdtext = context.Request.QueryString["SQL"];
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                int i = cmd.ExecuteNonQuery();
                cnn.Close();
                if (1 == i)
                {
                    result = "OK";
                }
                else
                {

                    result = "Hello,World!";
                }
                context.Response.Write(result);
            }
            else if ("getFshort" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                int width = Convert.ToInt32(context.Request.QueryString["width"]);
                int height= Convert.ToInt32(context.Request.QueryString["height"]);
                FileInfo f = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + wid + "/")).GetFiles()[0];
                System.Drawing.Image newimage = new Bitmap(width,height);
                Graphics g = Graphics.FromImage(newimage);
                g.DrawImage(new Bitmap(f.FullName), 0, 0, width, height);
                string filename=Guid.NewGuid().ToString("N")+".jpg";
                string path = context.Server.MapPath("/WallPapers/temp/") + filename;
                newimage.Save(path);
                context.Response.Clear();
                context.Response.ClearHeaders();
                context.Response.Buffer = false;
                context.Response.ContentType = "application/octet-stream"; 
                context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("cover.jpg", System.Text.Encoding.ASCII));
                context.Response.AppendHeader("Content-Length", (new FileInfo(path)).Length.ToString());
                context.Response.WriteFile(path);
                context.Response.Flush();
                File.Delete(path);
               

            }
            else if ("getFileLite" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                int width = Convert.ToInt32(context.Request.QueryString["width"]);
                int height = (int)Math.Round(width / 1.6, MidpointRounding.AwayFromZero);
                string fname = context.Request.QueryString["fname"];
                FileInfo f = new FileInfo(context.Server.MapPath("/WallPapers/" + wid + "/")+fname);
                Bitmap bmp = new Bitmap(f.FullName);
                int lw = bmp.Width;
                int lh = bmp.Height;
                int dw, dh;
                if ((float)lw / (float)lh > 1.6)
                {
                    dh = lh;
                    dw = (int)Math.Round(lh * 1.6, MidpointRounding.AwayFromZero); 
                }
                else {
                    dw = lw;
                    dh = (int)Math.Round(dw / 1.6, MidpointRounding.AwayFromZero); 
                }
                System.Drawing.Image tem = new Bitmap(dw, dh);
                Graphics gg = Graphics.FromImage(tem);
                gg.DrawImage(bmp, 0, 0, lw, lh);
                System.Drawing.Image newimage = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(newimage);
                g.DrawImage(new Bitmap(f.FullName), 0, 0, width, height);
                string filename = Guid.NewGuid().ToString("N") + f.Extension;
                string path = context.Server.MapPath("/WallPapers/temp/") + filename;
                newimage.Save(path);
                context.Response.Clear();
                context.Response.ClearHeaders();
                context.Response.Buffer = false;
                context.Response.ContentType = "application/octet-stream";
                context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.ASCII));
                context.Response.AppendHeader("Content-Length", (new FileInfo(path)).Length.ToString());
                context.Response.WriteFile(path);
                context.Response.Flush();
                File.Delete(path);
            }
            else if ("getAlter" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                int width = Convert.ToInt32(context.Request.QueryString["width"]);
                int height = Convert.ToInt32(context.Request.QueryString["height"]);
                string fname = context.Request.QueryString["fname"];
                FileInfo f = new FileInfo(context.Server.MapPath("/WallPapers/" + wid + "/") + fname);
                Bitmap bmp = new Bitmap(f.FullName);
                int lw = bmp.Width;
                int lh = bmp.Height;
                int dw, dh;
                if ((float)lw / (float)lh > 1.6)
                {
                    dh = lh;
                    dw = (int)Math.Round(lh * 1.6, MidpointRounding.AwayFromZero);
                }
                else
                {
                    dw = lw;
                    dh = (int)Math.Round(dw / 1.6, MidpointRounding.AwayFromZero);
                }
                System.Drawing.Image tem = new Bitmap(dw, dh);
                Graphics gg = Graphics.FromImage(tem);
                gg.DrawImage(bmp, 0, 0, lw, lh);
                System.Drawing.Image newimage = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(newimage);
                g.DrawImage(new Bitmap(f.FullName), 0, 0, width, height);
                string filename = Guid.NewGuid().ToString("N") + f.Extension;
                string path = context.Server.MapPath("/WallPapers/temp/") + filename;
                newimage.Save(path);
                context.Response.Clear();
                context.Response.ClearHeaders();
                context.Response.Buffer = false;
                context.Response.ContentType = "application/octet-stream";
                context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.ASCII));
                context.Response.AppendHeader("Content-Length", (new FileInfo(path)).Length.ToString());
                context.Response.WriteFile(path);
                context.Response.Flush();
                File.Delete(path);


            }
            else if ("getFileMd5" == context.Request.QueryString["action"])
            {
                string result="";
                string wid = context.Request.QueryString["wid"];
                string filename = context.Request.QueryString["fname"];
                if (wid != null && filename != null)
                {
                    string filepath=context.Server.MapPath("/WallPapers/" + wid + "/")+filename;
                    result= GetMD5(GetFileBytes(filepath));

                }
                context.Response.Write(result);
            }
            else if ("getNew" == context.Request.QueryString["action"])
            {

                string cmdtext = "select TOP(100) * from WallPaper order by creatDate desc";
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string id = rd["id"].ToString();
                    string title = rd["title"].ToString();
                    string cover = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + id + "/")).GetFiles()[0].Name;
                    result += "*" + id + "," + title +","+cover+ "#"+getFiles(id,context)+"#";
                }
                cnn.Close();
                if (result == "")
                {
                    result = "ER";
                }
                context.Response.Write(result);
            }
            else if ("getTime" == context.Request.QueryString["action"])
            {
                context.Response.Write(DateTime.Now.ToString("yyyyMMddHHmmss"));
            }
            else if ("getSorts" == context.Request.QueryString["action"])
            {
                string cmdtext = "select * from WallSort order by level desc";
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string sortid = rd["sortid"].ToString();
                    string sortName = rd["sortName"].ToString();
                    result += "*" + sortid + "," + sortName + "#";
                }
                cnn.Close();
                if (result == "")
                {
                    result = "ER";
                }
                context.Response.Write(result);
            }

            else if ("getSortList" == context.Request.QueryString["action"])
            {
                string sortid = context.Request.QueryString["sortid"];
                string cmdtext = "select * from WallPaper where SortID='" + sortid + "'";
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string id = rd["id"].ToString();
                    string title = rd["title"].ToString();
                    string cover = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + id + "/")).GetFiles()[0].Name;
                    result += "*" + id + "," + title + "," + cover + "#"+getFiles(id,context)+"#";
                }
                cnn.Close();
                if (result == "")
                {
                    result = "ER";
                }
                context.Response.Write(result);
            }

            else if ("Search" == context.Request.QueryString["action"])
            {
                string text = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(context.Request.QueryString["text"]));
                string cmdtext = "select * from WallPaper where Contents like '%" + text + "%' or title like '&" + text + "&'";
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string id = rd["id"].ToString();
                    string title = rd["title"].ToString();
                    string cover = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + id + "/")).GetFiles()[0].Name;
                    result += "*" + id + "," + title + "," + cover + "#";
                }
                cnn.Close();
                if (result == "")
                {
                    result = "ER";
                }
                context.Response.Write(result);
            }
            else if ("getHots" == context.Request.QueryString["action"])
            {
                string cmdtext = "select TOP(20) * from WallPaper order by ViewCount desc";
                string result = "";
                SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                SqlCommand cmd = cnn.CreateCommand();
                cmd.CommandText = cmdtext;
                cnn.Open();
                SqlDataReader rd = cmd.ExecuteReader();
                while (rd.Read())
                {
                    string id = rd["id"].ToString();
                    string title = rd["title"].ToString();
                    string cover = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + id + "/")).GetFiles()[0].Name;
                    result += "*" + id + "," + title + "," + cover + "#" + getFiles(id, context) + "#";
                }
                cnn.Close();
                if (result == "")
                {
                    result = "ER";
                }
                context.Response.Write(result);
            }
            else if ("getSingle" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                if (wid != null)
                {
                    string cmdtext = "select * from WallPaper where id='" + wid + "'";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {

                        string id = rd["id"].ToString();
                        string title = rd["title"].ToString();
                        string cover = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + id + "/")).GetFiles()[0].Name;
                   
                        result += id + "," + title + "," + cover;
                    }
                    cnn.Close();
                    if (result == "")
                    {
                        result = "ER";
                    }
                    context.Response.Write(result);
                }

            }
            else if ("SoftOpen" == context.Request.QueryString["action"])
            {
                string softid = context.Request.QueryString["sid"];
                string deviceid = context.Request.QueryString["did"];
                string info = context.Request.QueryString["info"];
                context.Response.Write(SoftLog(deviceid, softid, info));
            }

            else if ("getDetail" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                if (wid != null)
                {
                    string cmdtext = "select * from WallPaper where id='" + wid + "'";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    SqlDataReader rd = cmd.ExecuteReader();
                    while (rd.Read())
                    {

                        string Contents = rd["Contents"].ToString();
                        string ViewCount = rd["ViewCount"].ToString();
                        string creatDate = rd["creatDate"].ToString();
                        result += Contents + "," + ViewCount + "," + creatDate;
                    }
                    cnn.Close();
                    if (result == "")
                    {
                        result = "ER";
                    }
                    context.Response.Write(result);
                }

            }
            else if ("AddViews" == context.Request.QueryString["action"])
            {
                string wid = context.Request.QueryString["wid"];
                if (wid != null)
                {
                    string cmdtext = "select ViewCount from WallPaper where id='" + wid + "'";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    int count = (int)cmd.ExecuteScalar();
                    count++;
                    cmd.CommandText = "update WallPaper set ViewCount=" + count + " where id='" + wid + "'";
                    result = cmd.ExecuteNonQuery() == 1 ? "OK" : "ER";
                    cnn.Close();
                    if (result == "")
                    {
                        result = "ER";
                    }
                    context.Response.Write(result);
                }

            }
            
            else if ("uploadSETS" == context.Request.QueryString["action"])
            {
                string did = context.Request.QueryString["did"];
                string lidlist = context.Request.QueryString["lidlist"];
                string cid = context.Request.QueryString["cid"];
                if (null != did && null != lidlist && null != cid)
                {
                    string cmdtext = "insert into WallSets values('" + did + "','" + cid + "','" + lidlist + "','None')";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    int i = (int)cmd.ExecuteNonQuery();
                    if (i == 1)
                    {
                        result = "OK";
                    }
                    else
                    {
                        result = "ER";

                    }
                    cnn.Close();
                    context.Response.Write(result);
                }
            }
            else if ("updateSETS" == context.Request.QueryString["action"])
            {
                string did = context.Request.QueryString["did"];
                string lidlist = context.Request.QueryString["lidlist"];
                string cid = context.Request.QueryString["cid"];
                if (null != did && null != lidlist && null != cid)
                {
                    string cmdtext = "update WallSets set set curentWall='" + cid + "',LikeList='" + lidlist + "' where setid='" + did + "'";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    int i = (int)cmd.ExecuteNonQuery();
                    if (i == 1)
                    {
                        result = "OK";
                    }
                    else
                    {
                        result = "ER";

                    }
                    cnn.Close();
                    context.Response.Write(result);
                }
            }
            else if ("getSETS" == context.Request.QueryString["action"])
            {
                string did = context.Request.QueryString["did"];
                if (did != null)
                {
                    string cmdtext = "select count(*) from WallSets where setid='" + did + "'";
                    string cmdtext1 = "select * from WallSets where setid='" + did + "'";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    int i = (int)cmd.ExecuteScalar();
                    if (i == 1)
                    {
                        cmd.CommandText = cmdtext1;
                        SqlDataReader rd = cmd.ExecuteReader();
                        while (rd.Read())
                        {

                            string curentWall = rd["curentWall"].ToString();
                            string LikeList = rd["LikeList"].ToString();
                            string OtherInfo = rd["OtherInfo"].ToString();

                            result += "*" + curentWall + "," + LikeList + "," + OtherInfo + "#";
                        }
                    }

                    cnn.Close();
                    context.Response.Write(result);
                }
            }
            else if ("makeArgs" == context.Request.QueryString["action"])
            {
                string did = context.Request.QueryString["did"];
                string info = context.Request.QueryString["info"];
                string wid = context.Request.QueryString["wid"];
                if (null != did && null != info && null != wid)
                {
                    string aid = Guid.NewGuid().ToString("N");
                    string cmdtext = "insert into WallSets values('" + aid + "','" + info + "','" + wid + "','" + did + "')";
                    string result = "";
                    SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
                    SqlCommand cmd = cnn.CreateCommand();
                    cmd.CommandText = cmdtext;
                    cnn.Open();
                    int i = (int)cmd.ExecuteNonQuery();
                    if (i == 1)
                    {
                        result = "OK";
                    }
                    else
                    {
                        result = "ER";

                    }
                    cnn.Close();
                    context.Response.Write(result);
                }
            }
                
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        public string SoftLog(string devieceid,string softid, string info)
        {
            string logid = Guid.NewGuid().ToString("N");
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            string cmdtext = "insert into SoftLog values('" + logid + "','" + devieceid +  "','"+softid+"'," + time + ",'"+info+"')";
            string result = "";
            SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["constr"]);
            SqlCommand cmd = cnn.CreateCommand();
            cmd.CommandText = cmdtext;
            cnn.Open();
            int i = (int)cmd.ExecuteNonQuery();
            if (i == 1)
            {
                result = "OK";
            }
            else
            {
                result = "ER";

            }
            cnn.Close();
            return result;
        }
        public string getFiles(string wid,HttpContext context) {
            string result = "";
            FileInfo[] files = new DirectoryInfo(context.Server.MapPath("/WallPapers/" + wid + "/")).GetFiles();
            foreach (FileInfo f in files)
            {
                result += f.Name + ",";
            }
            if (result != "")
            {
                result = result.Substring(0, result.Length - 1);
            }
            else if (result == "")
            {
                result = "ER";
            }
            return result;
        }
        public static string GetMD5(byte[] str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in System.Security.Cryptography.MD5.Create().ComputeHash(str))
            {
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }
        public static byte[] GetFileBytes(string filapath)
        {
            FileInfo f = new FileInfo(filapath);
            byte[] b1 = new byte[512];
            byte[] b2 = new byte[512];
            FileStream aFile = new FileStream(filapath, FileMode.Open);
            aFile.Seek(0, SeekOrigin.Begin);
            aFile.Read(b1, 0, 512);
            aFile.Seek(f.Length - 512, SeekOrigin.Begin);
            aFile.Read(b2, 0, 512);
            aFile.Dispose();
            aFile.Close();
            return ComBytes(b1, b2);
        }
        public static byte[] ComBytes(byte[] a, byte[] b)
        {
            byte[] c = new byte[a.Length + b.Length];
            a.CopyTo(c, 0);
            b.CopyTo(c, a.Length);
            return c;
        }
    }
}